﻿using I_Authorization.Domains.Organization;
using I_Authorization.Infrastructure.Interface;
using I_Authorization.Read.API.Application.Commons.CottageCommons;
using MediatR;

namespace I_Authorization.Read.API.Application.CommandHandlers.CottageCommonsHandlers
{
    public class CottageShowCommonsHandlers : IRequestHandler<CottageShowCommons, Page<Cottage>>
    {
        private readonly ICottageRepository _cottage;

        public CottageShowCommonsHandlers(ICottageRepository cottage)
        {
            _cottage = cottage;
        }

        public async Task<Page<Cottage>> Handle(CottageShowCommons request, CancellationToken cancellationToken)
        {
            var List = await _cottage.GetAsync(c=>c.IsDel==false);
            if (!string.IsNullOrEmpty(request.CottageName)||request.CottageName!=null) 
            {
                List = List.Where(c => c.CottageName.Contains(request.CottageName)).ToList();
                List = await _cottage.GetAsync(c => c.CottageName.Contains(request.CottageName) && !c.IsDel == true);
            }
            int totalCount = List.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.size);
            List = List.OrderByDescending(c=>c.CottageId).Skip(request.size * (request.page - 1)).Take(request.size).ToList();

            return new Page<Cottage>
            {
                tatalCount = totalCount,
                pageCount = pageCount,
                Data = List
            };
        }
    }
}
